package com.ruoyi.common.sms;

import com.google.gson.Gson;
import com.jdcloud.sdk.auth.CredentialsProvider;
import com.jdcloud.sdk.auth.StaticCredentialsProvider;
import com.jdcloud.sdk.http.HttpRequestConfig;
import com.jdcloud.sdk.http.Protocol;
import com.jdcloud.sdk.service.sms.client.SmsClient;
import com.jdcloud.sdk.service.sms.model.BatchSendRequest;
import com.jdcloud.sdk.service.sms.model.BatchSendResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class JdSmsClient implements InitializingBean {
	private static SmsClient smsClient;

    // 地域信息不用修改
    @Value("${sms.region}")
    private String REGION;
    private static String region;

    // 请填写AccessKey ID
    @Value("${sms.accessKeyId}")
    private  String ACCESSKEYID;
    private static String accessKeyId;

    // 请填写AccessKey Secret
    @Value("${sms.secretAccessKey}")
    private  String SECRETACCESSKEY;
    private static String secretAccessKey;

    @Value("${sms.templateId}")
    private  String TEMPLATEID;
    private static String templateId;

    @Value("${sms.signId}")
    private  String SIGNID;
    private static String signId;

    public void init() {
        System.out.println(signId);
        CredentialsProvider credentialsProvider = new StaticCredentialsProvider(accessKeyId, secretAccessKey);
        smsClient = SmsClient.builder()
                .credentialsProvider(credentialsProvider)
                .httpRequestConfig(new HttpRequestConfig.Builder().protocol(Protocol.HTTP).build()) //默认为HTTPS
                .build();
    }
    
    /**
     * 指定模板发送短信验证码
     */
    public void sendCodeMsg(String phone,String code) {
        BatchSendRequest request = new BatchSendRequest();
        request.setRegionId(region);
        // 设置模板ID 应用管理-文本短信-短信模板 页面可以查看模板ID
        request.setTemplateId(templateId);
        // 设置签名ID 应用管理-文本短信-短信签名 页面可以查看签名ID
        request.setSignId(signId);
        // 设置下发手机号list
        List<String> phoneList = new ArrayList<>();
        phoneList.add(phone);
        request.setPhoneList(phoneList);
        // 设置模板参数，非必传，如果模板中包含变量请填写对应参数，否则变量信息将不做替换。
        List<String> params = new ArrayList<>();
        params.add(code);
        request.setParams(params);
        BatchSendResponse response = smsClient.batchSend(request);
        System.out.println(new Gson().toJson(response));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        region = this.REGION;
        accessKeyId = this.ACCESSKEYID;
        signId = this.SIGNID;
        templateId = this.TEMPLATEID;
        secretAccessKey = this.SECRETACCESSKEY;
    }
}
